package com.baor.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baor.dao.CouponDao;
import com.baor.dao.CouponUserDao;
import com.baor.dao.VipDao;
import com.baor.domain.*;
import com.baor.seacurity.TokenService;
import com.baor.service.AppletService;
import com.baor.service.ProgramService;
import com.baor.utils.AjaxResult;
import com.baor.utils.HttpRequestUtil;
import com.baor.utils.MD5Utils;
import com.baor.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class ProgramServiceImpl implements ProgramService {
    @Autowired
    private CouponDao couponDao;
    @Autowired
    private CouponUserDao couponUserDao;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private VipDao vipDao;
    @Value("${sys.default.pwd}")
    private String defaultPwd;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AppletService appletService;
    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String wxsecret;

    private UserVo vo;

    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    @Override
    public AjaxResult<?> list(Map<String,Object> params) {
        List<CouponUserVo> vo = this.couponUserDao.couponList(params);
        for(int i = 0 ; i<vo.size();i++){
            int couponId = vo.get(i).getCouponId();
            CouponVo couponVo = new CouponVo();
            couponVo.setCouponId(couponId);
            couponVo.setCouponStatus(String.valueOf(1));
            int row = this.couponDao.updateById(couponVo);
        }
        int pageIndex = (int) params.get("pageIndex");
        int pageSize = (int) params.get("pageSize");
        params.put("pageIndex",(pageIndex - 1)*pageSize);
        Map<String,Object> res = this.couponDao.findPageCount(params);
        res.put("couponList",this.couponDao.list(params));
        return AjaxResult.success(res);
    }

    @Override
    public AjaxResult<?> addCouponUser(CouponUserVo vo) {
        LocalDateTime currentDate = LocalDateTime.now();
        System.out.println(currentDate);
        LocalDateTime dateAfter30Days = currentDate.plusDays(vo.getExpiryDay());
        vo.setReceiveTime(String.valueOf(currentDate));
        vo.setExpireTime(String.valueOf(dateAfter30Days));
        int row  = this.couponUserDao.insert(vo);
        if(row > 0){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult<?> useCoupon(CouponUserVo vo) {
        LocalDateTime currentDate = LocalDateTime.now();
        vo.setUsedTime(String.valueOf(currentDate));
        vo.setStatus("1");
        int row = this.couponUserDao.useCoupon(vo);
        if(row > 0){
            return AjaxResult.success();
        }else{
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult<?> login(UserVo userVo) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String requestPath = attributes.getRequest().getRequestURI();
        userVo.setUserPassword(MD5Utils.md5(userVo.getUserPassword()));
        Map<String,Object> res = new HashMap<>();
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 查询
        UserVo userVos = this.vipDao.SelectUserList(userVo);

        if(userVos != null && !userVos.equals("")){
            vo =  userVos;
        }else{
            return  AjaxResult.error("登陆失败");

        }
        // 存储openid
        if(userVo.getCode() != null && !userVo.getCode().equals("")){
            AuthorizationUtil authorizationUtil = new AuthorizationUtil();
            authorizationUtil.setCode(userVo.getCode());
            String openid = (String) addGrantUser(authorizationUtil).getData();
            if(openid.equals("微信授权失败")){
                return AjaxResult.error("授权登陆失败");
            }else{
                UserVo vo1 = new UserVo();
                vo1.setUserId(vo.getUserId());
                vo1.setWxOpenid(openid);
                int row = this.vipDao.updateById(vo1);
            }
        }
            // 更新重新获取一次vo
            UserVo updateVo = this.vipDao.SelectUserList(userVo);
            String token = tokenService.createToken(vo);
            redisUtil.setValue("userAccount:"+vo.getUserAccount(),vo);
            redisUtil.setValue("token:"+vo.getUserAccount(),token);
            res.put("authorization",token);
            res.put("user", updateVo);
            return AjaxResult.success(res);
    }

    @Override
    public AjaxResult<?> enroll(UserVo userVo) {
        //账号
        List<UserVo> vo = this.vipDao.check(userVo.getUserTel());
        if(vo == null || vo.isEmpty() || vo.equals("")){
            String account = generateAccount(10);
            userVo.setUserAccount(account);
            //用户名
            if(userVo.getUserName() == null || userVo.getUserName().equals("")){
                userVo.setUserName("新用户"+generateAccount(4));
            }
            //加密
            String pwd = MD5Utils.md5(userVo.getUserPassword());
            userVo.setUserPassword(pwd);
            //注册时间
            LocalDateTime now = LocalDateTime.now();
            userVo.setCreateTime(String.valueOf(now));
            //注册来源
            userVo.setOrderSourceId(String.valueOf(1));
            int row = this.vipDao.insert(userVo);
            this.appletService.registIf(userVo.getUserId());
            if(row > 0){
                return AjaxResult.success();
            }else{
                return AjaxResult.error();
            }
        }else{
            return AjaxResult.error("该手机号已经注册");
        }

    }

    @Override
    public AjaxResult<?> addGrantUser(AuthorizationUtil authorizationUtil) {
        Map<String,Object> map = new HashMap<>();
        String params = "appid="+appid+"&secret="+wxsecret+"&js_code="+authorizationUtil.getCode()+"&grant_type=authorization_code";
        String str = HttpRequestUtil.sendGet("https://api.weixin.qq.com/sns/jscode2session",params);
        JSONObject json = JSONObject.parseObject(str);
        System.out.println(params);
        int code = 0;
        String openId = "";
        if(json.get("errcode")!= null){
            code = (int) json.get("errcode");
            if(code == 0 ){
                openId = (String) json.get("openid");
                return AjaxResult.success(openId);
            }else{
                String str1 = "微信授权失败";
                System.out.println(json);
                return AjaxResult.error(str1);
            }
        }else{
            openId = (String) json.get("openid");
            return AjaxResult.success(openId);
        }
    }

    public static String generateAccount(int length) {
        StringBuilder account = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(CHARACTERS.length());
            char randomChar = CHARACTERS.charAt(randomIndex);
            account.append(randomChar);
        }

        return account.toString();
    }
}
